﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Text;
using System.Threading;
using System.Drawing;
using System.Text.RegularExpressions;

public partial class TrackingManage_TrackingList : BasePage
{
    ISendTruckHandler stManager = new SendTruckHandler();
    DataBase db = new DataBase();
    string language = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        language = Thread.CurrentThread.CurrentUICulture.ToString().ToLower();
        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                ISystemHandler sysManage = new SystemHandler();
                string strPermission = sysManage.GetLoginUserPermissions();
                if (!strPermission.Contains("1066"))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }
            }

            ViewState["OrderBy"] = "SendCodeForOrder";
            ViewState["Accending"] = "desc";
            dataBind();
            initSearchBox();
        }
    }

    private void initSearchBox()
    {
        fillShipper();
        fillWhouse();
        fillVendor();
    }

    private void fillShipper()
    {
        ISyClientHandler clientManager = new SyClientHandler();
        DataTable dt = clientManager.GetClientListByTypeID(int.Parse(Enums.CT.TYR.ToString("d")));
        lstShipper.DataSource = dt;

        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            lstShipper.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            lstShipper.DataTextField = "HKShortName";
        }
        else
        {
            lstShipper.DataTextField = "CNShortName";
        }
        lstShipper.DataValueField = "PKID";
        lstShipper.DataBind();
    }

    private void fillWhouse()
    {
        ISyClientHandler clientManager = new SyClientHandler();
        string sqlStr = "SELECT DISTINCT client.* FROM Sy_Client client " +
                        " inner join Sy_ClientType type on client.PKID = type.ClientID " +
                        " inner join Sy_Code code on type.SyCodeID = code.PKID" +
                        " where code.Type='CT' and (code.Code = 'MT' or code.Code = 'CK') AND client.Status = 1";
        DataTable dt = clientManager.GetClientList(sqlStr, null);
        ddlWhouse.DataSource = dt;
        ddlWhouse.DataTextField = ("en".Equals(language) ? "ENGShortName" : ("zh-hk".Equals(language) ? "HKShortName" : "CNShortName"));
        ddlWhouse.DataValueField = "PKID";
        ddlWhouse.DataBind();
        ddlWhouse.Items.Insert(0, new ListItem("select...", "0"));
    }

    private void fillVendor()
    {
        ISyClientHandler clientManager = new SyClientHandler();
        string sqlStr = @"SELECT DISTINCT client.* FROM Sy_Client client 
                         inner join Sy_ClientType type on client.PKID = type.ClientID
                         inner join Sy_Code code on type.SyCodeID = code.PKID
                         where code.Type='CT' and code.Code = 'GQ' AND client.Status = 1";

        DataTable dt = clientManager.GetClientList(sqlStr, null);
        ddlVendor.DataSource = dt;
        ddlVendor.DataTextField = ("en".Equals(language) ? "ENGShortName" : ("zh-hk".Equals(language) ? "HKShortName" : "CNShortName"));
        ddlVendor.DataValueField = "PKID";
        ddlVendor.DataBind();
        ddlVendor.Items.Insert(0, new ListItem("select...", "0"));
    }


    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string sqlstr, ref SqlParameter[] parms)
    {
        List<SqlParameter> list = new List<SqlParameter>();
        sqlstr = "";
        
        if (ViewState["Shipper"] != null)
        {
            sqlstr += " and (soDtl.ShipperID in (" + ViewState["Shipper"] + ")) ";
        }
        if (ViewState["Whouse"] != null)
        {
            list.Add(new SqlParameter("@Whouse", ViewState["Whouse"].ToString()));
            sqlstr += " and whouse.PKID = @Whouse";
        }
        if (ViewState["Vendor"] != null)
        {
            list.Add(new SqlParameter("@Vendor", ViewState["Vendor"].ToString()));
            sqlstr += " and vendor.PKID = @Vendor";
        }
        if (ViewState["JobDateFrom"] != null && ViewState["JobDateTo"] != null)
        {
            list.Add(new SqlParameter("@JobDateFrom", ViewState["JobDateFrom"].ToString()));
            list.Add(new SqlParameter("@JobDateTo", ViewState["JobDateTo"].ToString()));
            sqlstr += " and soDtl.JobDate BETWEEN @JobDateFrom AND @JobDateTo";
        }
        else if (ViewState["JobDateFrom"] != null && ViewState["JobDateTo"] == null)
        {
            list.Add(new SqlParameter("@JobDateFrom", ViewState["JobDateFrom"].ToString()));
            sqlstr += " and soDtl.JobDate >= @JobDateFrom";
        }
        else if (ViewState["JobDateFrom"] == null && ViewState["JobDateTo"] != null)
        {
            list.Add(new SqlParameter("@JobDateTo", ViewState["JobDateTo"].ToString()));
            sqlstr += " and soDtl.JobDate <= @JobDateTo";
        }

        // 如果当前登录用户有所属公司，则只查出该公司
        if (Session["LoginUserClientID"].ToString() != "0")
        {
            sqlstr = sqlstr + " and st.Contractor =" + Session["LoginUserClientID"].ToString();
        }
        parms = list.ToArray();
    }

    private void dataBind()
    {
        string sqlStr = @"SELECT DISTINCT so.Appointament, vendor.CNShortName as Vendor, vendor.HKShortName as HKVendor, vendor.ENGShortName as ENGVendor,
                            whouse.CNShortName as Whouse, whouse.HKShortName as HKWhouse, whouse.ENGShortName as ENGWhouse,
                            contractor.CNShortName as Contractor, contractor.HKShortName as HKContractor, contractor.ENGShortName as ENGContractor,
                            contractor.PKID as ContractorID,
                            soDtl.JobDate, truckType.Model as TruckType, truck.LicenseNO, st.SendCode as SendCodeForOrder,
                            CAST(st.SendCode AS varchar) + ',' + CAST(truck.PKID as varchar) as SendCode, vendor.PKID as VendorID
                        FROM (
	                        SELECT DISTINCT stDtl.TruckID, st.SendCode, stDtl.TypeID
	                        FROM BN_SendTruck st INNER JOIN
		                        BN_SendTruckDtl stDtl ON st.PKID = stDtl.SendTruckID
                        ) AS SendTruck LEFT JOIN
	                        BN_SendTruck st ON SendTruck.SendCode = st.SendCode LEFT JOIN
	                        BN_ShippingOrder so ON st.OrderID = so.PKID LEFT JOIN
	                        BN_ShippingOrderDtl soDtl ON so.PKID = soDtl.OrderID LEFT JOIN
                            Sy_Client vendor ON so.VendorID = vendor.PKID LEFT JOIN
                            Sy_Client contractor ON so.Contractor = contractor.PKID LEFT JOIN
                            Sy_Client whouse ON soDtl.WhouseID = whouse.PKID LEFT JOIN
                            BN_Truck truck ON SendTruck.TruckID = truck.PKID LEFT JOIN
                            Sy_ContainerModel truckType ON SendTruck.TypeID = truckType.PKID
                        WHERE (so.Status = " + HK2009.Common.Enums.ShippingOrderStatus.CHECK.ToString("d") + 
                       " or so.Status = " + HK2009.Common.Enums.ShippingOrderStatus.CONFIM.ToString("d") +
                       " or so.Status = " + HK2009.Common.Enums.ShippingOrderStatus.PRINT.ToString("d") + ")";
        SqlParameter[] parms = null;
        string clause = string.Empty;
        ProcessParms(ref clause, ref parms);
        sqlStr += clause;

        DataTable dt = stManager.GetList(sqlStr, parms);
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
        gvSendTruckList.DataSource = view;
        gvSendTruckList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotal.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotal.Text = "0";
        }
    }

    protected void gvSendTruckList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvSendTruckList.PageIndex = e.NewPageIndex;
        dataBind();

    }
    protected void gvSendTruckList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dataBind();

    }
    protected void gvSendTruckList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBind();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (lstSelShipper.Items.Count > 0)
        {
            string item = string.Empty;
            for (int i = 0; i < lstSelShipper.Items.Count; i++)
            {
                item += lstSelShipper.Items[i].Value + ",";
            }
            ViewState["Shipper"] = item.Substring(0, item.Length - 1);
        }
        else
        {
            ViewState["Shipper"] = null;
        }
        if (ddlWhouse.SelectedValue != "0")
        {
            ViewState["Whouse"] = ddlWhouse.SelectedValue;
        }
        else
        {
            ViewState["Whouse"] = null;
        }
        if (ddlVendor.SelectedValue != "0")
        {
            ViewState["Vendor"] = ddlVendor.SelectedValue;
        }
        else
        {
            ViewState["Vendor"] = null;
        }
        if (txtJobDateFrom.Text != null && txtJobDateFrom.Text.Trim() != "")
        {
            try
            {
                DateTime.Parse(txtJobDateFrom.Text.Trim());
                ViewState["JobDateFrom"] = txtJobDateFrom.Text.Trim();
            }
            catch { ViewState["JobDateFrom"] = null; }
        }
        else
        {
            ViewState["JobDateFrom"] = null;
        }
        if (txtJobDateTo.Text != null && txtJobDateTo.Text.Trim() != "")
        {
            try
            {
                DateTime.Parse(txtJobDateTo.Text.Trim());
                ViewState["JobDateTo"] = txtJobDateTo.Text.Trim();
            }
            catch
            {
                ViewState["JobDateTo"] = null;
            }
        }
        else
        {
            ViewState["JobDateTo"] = null;
        }
        
        dataBind();
        gvDetailList.DataSource = null;
        gvDetailList.DataBind();
        gvTrackingList.DataSource = null;
        gvTrackingList.DataBind();
    }

    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvSendTruckList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBind();
    }

    protected void gvSendTruckList_SelectedIndexChanged(object sender, EventArgs e)
    {
        HiddenField hidSendCode = (HiddenField)gvSendTruckList.SelectedRow.FindControl("hidSendCode");
        HiddenField hidOrnVendorID = (HiddenField)gvSendTruckList.SelectedRow.FindControl("hidOrnVendorID");
        HiddenField hidOrnJobDate = (HiddenField)gvSendTruckList.SelectedRow.FindControl("hidOrnJobDate");

        hidSendCode2.Value = "";
        hidTruckID.Value = "";
        hidVendorID.Value = "";
        hidJobDate.Value = "";

        if (hidSendCode != null && !"".Equals(hidSendCode.Value))
        {
            string[] sendCodeTruckID = hidSendCode.Value.Split(',');

            // 设置选中的派车的标识信息
            hidSendCode2.Value = sendCodeTruckID[0];
            hidTruckID.Value = sendCodeTruckID[1];
            hidVendorID.Value = hidOrnVendorID.Value;
            hidJobDate.Value = hidOrnJobDate.Value;

            ISendTruckHandler sendTruckManager = new SendTruckHandler();
            // 查找job详细
            string sql = @"SELECT soDtl.SONO, soDtl.Vol as CBM, soDtl.GrossWT as Kgs, so.MateReceiptDate as MateDate
                            FROM BN_ShippingOrder so INNER JOIN
                                BN_ShippingOrderDtl soDtl ON so.PKID = soDtl.OrderID
                            WHERE so.PKID IN (
                                SELECT DISTINCT OrderID FROM BN_SendTruck st INNER JOIN
                                    BN_SendTruckDtl stDtl ON st.PKID = stDtl.SendTruckID
                                WHERE st.SendCode = @SendCode
                            )";
            SqlParameter[] parms = new SqlParameter[1];
            parms[0] = new SqlParameter("@SendCode", sendCodeTruckID[0]);

            DataTable dt = sendTruckManager.GetList(sql, parms);
            gvDetailList.DataSource = dt;
            gvDetailList.DataBind();

            // 查找所有的车辆动态 
//            sql = @"SELECT DISTINCT truckStatus.*, tracking.CBDate, tracking.CEDate, tracking.PKID as TrackingID
//                    FROM Sy_TruckStatus truckStatus LEFT JOIN
//                        BN_TTracking tracking ON truckStatus.PKID = tracking.TruckStatusID AND tracking.TruckID = @TruckID LEFT JOIN
//                        BN_SendTruck st ON tracking.SendTruckID = st.PKID AND st.SendCode = @SendCode LEFT JOIN
//                        BN_SendTruckDtl stDtl ON st.PKID = stDtl.SendTruckID
//                    ORDER BY truckStatus.Sequence ASC;";
            sql = "SELECT * FROM Sy_TruckStatus WHERE Status = 1 ORDER BY Sequence";
            //parms = new SqlParameter[2];
            //parms[0] = new SqlParameter("@TruckID", sendCodeTruckID[1]);
            //parms[1] = new SqlParameter("@SendCode", sendCodeTruckID[0]);

            //dt = sendTruckManager.GetList(sql, parms);
            dt = sendTruckManager.GetList(sql, new SqlParameter[]{});
            gvTrackingList.DataSource = dt;
            gvTrackingList.DataBind();

            // 获得SendTruckID和TruckID
//            sql = @"SELECT TOP 1 st.PKID FROM BN_SendTruck st INNER JOIN
//                        BN_SendTruckDtl stDtl ON st.PKID = stDtl.SendTruckID
//                    WHERE st.SendCode = @SendCode AND stDtl.TruckID = @TruckID";
//            parms = new SqlParameter[2];
//            parms[0] = new SqlParameter("@SendCode", sendCodeTruckID[0]);
//            parms[1] = new SqlParameter("@TruckID", sendCodeTruckID[1]);
//            dt = sendTruckManager.GetList(sql, parms);

//            if (dt != null && dt.Rows.Count > 0)
//            {
//                string stid = dt.Rows[0][0].ToString();

//                hidSendTruckID.Value = stid;
//                hidTruckID.Value = sendCodeTruckID[1];
//            }
        }
        else
        {
            gvDetailList.DataSource = null;
            gvDetailList.DataBind();
            gvTrackingList.DataSource = null;
            gvTrackingList.DataBind();
        }

        gvSendTruckList.SelectedRowStyle.BackColor = Color.LightGreen;
        gvSendTruckList.SelectedRow.BackColor = Color.LightGreen;

        HiddenField hidContractorID = (HiddenField)gvSendTruckList.SelectedRow.FindControl("hidContractorID");
        if (!"".Equals(hidContractorID.Value))
        {
            ISyClientHandler clientManager = new SyClientHandler();
            Sy_ClientQuery ctr = clientManager.GetClient(int.Parse(hidContractorID.Value));
            if (ctr != null && ctr.GPSWebsite != null && !"".Equals(ctr.GPSWebsite))
            {
                lbtnGps.HRef = ctr.GPSWebsite.ToLower().StartsWith("http") ? ctr.GPSWebsite : "http://" + ctr.GPSWebsite;
                lbtnGps.Visible = true;
            }
        }
    }

    protected void gvSendTruckList_RowCreated(object sender, GridViewRowEventArgs e)
    {
        e.Row.Cells[0].Attributes.Add("style", "display:none;");
    }

    protected void gvSendTruckList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblVendor = (Label)e.Row.FindControl("lblVendor");
            Label lblHKVendor = (Label)e.Row.FindControl("lblHKVendor");
            Label lblENGVendor = (Label)e.Row.FindControl("lblENGVendor");

            Label lblWhouse = (Label)e.Row.FindControl("lblWhouse");
            Label lblHKWhouse = (Label)e.Row.FindControl("lblHKWhouse");
            Label lblENGWhouse = (Label)e.Row.FindControl("lblENGWhouse");

            Label lblContractor = (Label)e.Row.FindControl("lblContractor");
            Label lblHKContractor = (Label)e.Row.FindControl("lblHKContractor");
            Label lblENGContractor = (Label)e.Row.FindControl("lblENGContractor");

            if ("en".Equals(language))
            {
                lblVendor.Visible = false;
                lblHKVendor.Visible = false;
                lblENGVendor.Visible = true;

                lblWhouse.Visible = false;
                lblHKWhouse.Visible = false;
                lblENGWhouse.Visible = true;

                lblContractor.Visible = false;
                lblHKContractor.Visible = false;
                lblENGContractor.Visible = true;
            }
            else if ("zh-hk".Equals(language))
            {
                lblVendor.Visible = false;
                lblHKVendor.Visible = true;
                lblENGVendor.Visible = false;

                lblWhouse.Visible = false;
                lblHKWhouse.Visible = true;
                lblENGWhouse.Visible = false;

                lblContractor.Visible = false;
                lblHKContractor.Visible = true;
                lblENGContractor.Visible = false;
            }
            else
            {
                lblVendor.Visible = true;
                lblHKVendor.Visible = false;
                lblENGVendor.Visible = false;

                lblWhouse.Visible = true;
                lblHKWhouse.Visible = false;
                lblENGWhouse.Visible = false;

                lblContractor.Visible = true;
                lblHKContractor.Visible = false;
                lblENGContractor.Visible = false;
            }

            // 读取最后动态
            HiddenField hidSendCode = (HiddenField)e.Row.FindControl("hidSendCode");
            HiddenField hidOrnVendorID = (HiddenField)e.Row.FindControl("hidOrnVendorID");
            HiddenField hidOrnJobDate = (HiddenField)e.Row.FindControl("hidOrnJobDate");

            if (hidSendCode != null && !"".Equals(hidSendCode.Value))
            {
                string[] sendCodeTruck = hidSendCode.Value.Split(',');
                string sql = @"SELECT TOP 1 truckStatus.*, tracking.CBDate, tracking.CEDate
                        FROM BN_SendTruck st INNER JOIN
                            BN_TTracking tracking on st.PKID = tracking.SendTruckID INNER JOIN
                            Sy_TruckStatus truckStatus on tracking.TruckStatusID = truckStatus.PKID INNER JOIN
                            BN_ShippingOrder so ON st.OrderID = so.PKID INNER JOIN
                            BN_ShippingOrderDtl soDtl ON so.PKID = soDtl.OrderID
                        WHERE st.SendCode = @SendCode AND tracking.TruckID = @TruckID AND
                            so.VendorID = @VendorID AND soDtl.JobDate = @JobDate AND
                            tracking.CEDate IS NOT NULL AND tracking.CEDate != ''
                        ORDER BY truckStatus.Sequence DESC";
                List<SqlParameter> parmsList = new List<SqlParameter>();
                parmsList.Add(new SqlParameter("@SendCode", sendCodeTruck[0]));
                parmsList.Add(new SqlParameter("@TruckID", sendCodeTruck[1]));
                parmsList.Add(new SqlParameter("@VendorID", hidOrnVendorID.Value));
                parmsList.Add(new SqlParameter("@JobDate", hidOrnJobDate.Value));

                DataTable dt = stManager.GetList(sql, parmsList.ToArray());
                if (dt != null && dt.Rows.Count > 0)
                {
                    Label lblLastTracking = (Label)e.Row.FindControl("lblLastTracking");
                    Label lblCBDate = (Label)e.Row.FindControl("lblCBDate");
                    if ("en".Equals(language))
                    {
                        lblLastTracking.Text = dt.Rows[0]["ENGStatusName"].ToString();
                    }
                    else if ("zh-hk".Equals(language))
                    {
                        lblLastTracking.Text = dt.Rows[0]["HKStatusName"].ToString();
                    }
                    else
                    {
                        lblLastTracking.Text = dt.Rows[0]["StatusName"].ToString();
                    }
                    if (dt.Rows[0]["CBDate"] != null && dt.Rows[0]["CBDate"].ToString() != string.Empty)
                    {
                        string cbDate = string.Format("{0:yyyy-MM-dd HH:mm}", dt.Rows[0]["CBDate"]);
                        lblCBDate.Text = cbDate;
                    }

                    else if (dt.Rows[0]["CEDate"] != null && dt.Rows[0]["CEDate"].ToString() != string.Empty)
                    {
                        string ceDate = dt.Rows[0]["CEDate"].ToString();
                        if (ceDate != null && !"".Equals(ceDate))
                        {
                            DateTime tmpDate = DateTime.Parse(ceDate);
                            if (tmpDate < DateTime.Now)
                            {
                                e.Row.ForeColor = Color.Red;
                            }
                        }
                    }
                }
            }

            //鼠标移动到某行上，该行变色
            e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#999999'");

            //鼠标移开后，恢复
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");

            //点击后，实现该行的选中
            e.Row.Attributes.Add("onclick", "__doPostBack('ctl00$ContentPlaceHolder1$gvSendTruckList','Select$" + e.Row.RowIndex + "')");
        }
    }

    protected void gvTrackingList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblStatusName = (Label)e.Row.FindControl("lblStatusName");
            Label lblHKStatusName = (Label)e.Row.FindControl("lblHKStatusName");
            Label lblENGStatusName = (Label)e.Row.FindControl("lblENGStatusName");

            if ("en".Equals(language))
            {
                lblStatusName.Visible = false;
                lblHKStatusName.Visible = false;
                lblENGStatusName.Visible = true;
            }
            else if ("zh-hk".Equals(language))
            {
                lblStatusName.Visible = false;
                lblHKStatusName.Visible = true;
                lblENGStatusName.Visible = false;
            }
            else
            {
                lblStatusName.Visible = true;
                lblHKStatusName.Visible = false;
                lblENGStatusName.Visible = false;
            }

            HiddenField hidTruckStatusID = (HiddenField)e.Row.FindControl("hidTruckStatusID");
            
            string sql = @"SELECT tracking.PKID, tracking.CBDate, tracking.CEDate
                        FROM BN_TTracking tracking INNER JOIN
	                        BN_SendTruck st ON tracking.SendTruckID = st.PKID INNER JOIN
	                        BN_ShippingOrder so ON st.OrderID = so.PKID INNER JOIN
	                        BN_ShippingOrderDtl soDtl ON so.PKID = soDtl.OrderID
                        WHERE tracking.TruckStatusID = @TruckStatusID AND
	                        st.SendCode = @SendCode AND
	                        tracking.TruckID = @TruckID AND
	                        so.VendorID = @VendorID";
            List<SqlParameter> parmsList = new List<SqlParameter>();
            parmsList.Add(new SqlParameter("@TruckStatusID", hidTruckStatusID.Value));
            parmsList.Add(new SqlParameter("@SendCode", hidSendCode2.Value));
            parmsList.Add(new SqlParameter("@TruckID", hidTruckID.Value));
            parmsList.Add(new SqlParameter("@VendorID", hidVendorID.Value));
            if (hidJobDate.Value == null || "".Equals(hidJobDate.Value))
            {
                sql += " AND soDtl.JobDate is null";
            }
            else
            {
                sql += " AND soDtl.JobDate = @JobDate";
                parmsList.Add(new SqlParameter("@JobDate", hidJobDate.Value));
            }

            DataTable dt = stManager.GetList(sql, parmsList.ToArray());
            if (dt != null && dt.Rows.Count > 0)
            {
                HiddenField hidTrackingID = (HiddenField)e.Row.FindControl("hidTrackingID");
                TextBox txtModCEDate = (TextBox)e.Row.FindControl("txtModCEDate");
                TextBox txtModCEDateH = (TextBox)e.Row.FindControl("txtModCEDateH");
                TextBox txtModCBDate = (TextBox)e.Row.FindControl("txtModCBDate");
                TextBox txtModCBDateH = (TextBox)e.Row.FindControl("txtModCBDateH");
                hidTrackingID.Value = dt.Rows[0]["PKID"].ToString();
                txtModCEDate.Text = string.Format("{0:yyyy-MM-dd}", dt.Rows[0]["CEDate"]);
                txtModCEDateH.Text = string.Format("{0:HHmm}", dt.Rows[0]["CEDate"]);
                txtModCBDate.Text = string.Format("{0:yyyy-MM-dd}", dt.Rows[0]["CBDate"]);
                txtModCBDateH.Text = string.Format("{0:HHmm}", dt.Rows[0]["CBDate"]);
            }
        }
    }

    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvSendTruckList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvSendTruckList.PageCount)
            {
                this.gvSendTruckList.PageIndex = i;
                //数据绑定
                dataBind();
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
                return;
            }
        }
        catch
        {
            Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
        }
    }

    /// <summary>
    /// 保存车辆动态
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string truckID = hidTruckID.Value;
        string sendCode = hidSendCode2.Value;
        string vendorId = hidVendorID.Value;
        string jobDate = hidJobDate.Value;

        if ("".Equals(truckID) || "".Equals(sendCode))
        {
            Jscript.AlertInAjax(Resources.Messages.AddFailed, UpdatePanel1);
            return;
        }

        string sqlStr = "";
        IBNTrackingHandler trackingManager = new BNTrackingHandler();
        List<SqlParameter> parmsList = new List<SqlParameter>();
        Regex dateReg = new Regex("((1[89]\\d{2})|([2-8]\\d{3}))[-](([1][012])|(0{1}[1-9]))[-]((3[01])|([12]\\d)|(0{1}[1-9]))");
        Regex timeReg = new Regex("(([0][0-9])|([1][0-9])|([2][0-3]))([0-5][0-9])");

        parmsList.Add(new SqlParameter("@TruckID", truckID));
        parmsList.Add(new SqlParameter("@SendCode", sendCode));
        parmsList.Add(new SqlParameter("@CreatedUser", Session["UserID"].ToString()));
        parmsList.Add(new SqlParameter("@VendorID", vendorId));

        if (jobDate != null && !"".Equals(jobDate))
        {
            parmsList.Add(new SqlParameter("@JobDate", jobDate));
        }

        foreach (GridViewRow row in gvTrackingList.Rows)
        {
            HiddenField hidTruckStatusID = (HiddenField)row.FindControl("hidTruckStatusID");
            HiddenField hidTrackingID = (HiddenField)row.FindControl("hidTrackingID");
            TextBox txtModCBDate = (TextBox)row.FindControl("txtModCBDate");
            TextBox txtModCBDateH = (TextBox)row.FindControl("txtModCBDateH");
            TextBox txtModCEDate = (TextBox)row.FindControl("txtModCEDate");
            TextBox txtModCEDateH = (TextBox)row.FindControl("txtModCEDateH");
            string cbDate = txtModCBDate.Text.Trim() + StringUtil.GetTime(txtModCBDateH.Text.Trim());
            string ceDate = txtModCEDate.Text.Trim() + StringUtil.GetTime(txtModCEDateH.Text.Trim());

            if (!dateReg.IsMatch(cbDate))
            {
                cbDate = null;
            }
            if (!timeReg.IsMatch(ceDate))
            {
                ceDate = null;
            }

            if (hidTrackingID.Value != null && !"".Equals(hidTrackingID.Value.Trim()))
            {
                if (cbDate == null)
                {
                    sqlStr += "UPDATE BN_TTracking SET CBDate=null,";
                }
                else
                {
                    sqlStr += "UPDATE BN_TTracking SET CBDate=@CBDate" + hidTruckStatusID.Value + ",";
                    parmsList.Add(new SqlParameter("@CBDate" + hidTruckStatusID.Value, cbDate));
                }

                if (ceDate == null)
                {
                    sqlStr += "CEDate=null,";
                }
                else
                {
                    sqlStr += "CEDate=@CEDate" + hidTruckStatusID.Value + ",";
                    parmsList.Add(new SqlParameter("@CEDate" + hidTruckStatusID.Value, ceDate));
                }

                sqlStr += @"CreatedUser=@CreatedUser,CreatedDate=GETDATE()
                     FROM BN_TTracking tracking INNER JOIN
                            BN_SendTruck st ON tracking.SendTruckID = st.PKID INNER JOIN
	                        BN_ShippingOrder so ON st.OrderID = so.PKID INNER JOIN
	                        BN_ShippingOrderDtl soDtl ON so.PKID = soDtl.OrderID
                        WHERE tracking.TruckID = @TruckID AND
	                        st.SendCode = @SendCode AND
	                        tracking.TruckStatusID = @TruckStatusID" + hidTruckStatusID.Value + " AND so.VendorID = @VendorID";
                if (jobDate == null || "".Equals(jobDate))
                {
                    sqlStr += " AND soDtl.JobDate IS NULL;";
                }
                else
                {
                    sqlStr += " AND soDtl.JobDate = @JobDate;";
                }

                parmsList.Add(new SqlParameter("@TruckStatusID" + hidTruckStatusID.Value, hidTruckStatusID.Value));
            }
            else if (cbDate != null || ceDate != null)
            {
                sqlStr += @"INSERT INTO BN_TTracking(TruckID,SendTruckID, TruckStatusID,CBDate,CEDate,CreatedUser,CreatedDate)
                            SELECT @TruckID, st.PKID,@TruckStatusID" + hidTruckStatusID.Value;
                if (cbDate == null)
                {
                    sqlStr += ",null";
                }
                else
                {
                    sqlStr += ",@CBDate" + hidTruckStatusID.Value;
                    parmsList.Add(new SqlParameter("@CBDate" + hidTruckStatusID.Value, cbDate));
                }

                if (ceDate == null)
                {
                    sqlStr += ",null";
                }
                else
                {
                    sqlStr += ",@CEDate" + hidTruckStatusID.Value;
                    parmsList.Add(new SqlParameter("@CEDate" + hidTruckStatusID.Value, ceDate));
                }

                sqlStr += @",@CreatedUser,GETDATE()
                            FROM BN_SendTruck st INNER JOIN
                                BN_SendTruckDtl stDtl ON st.PKID = stDtl.SendTruckID INNER JOIN
                                BN_ShippingOrder so ON st.OrderID = so.PKID INNER JOIN
                                BN_ShippingOrderDtl soDtl ON so.PKID = soDtl.OrderID
                            WHERE stDtl.TruckID=@TruckID AND st.SendCode=@SendCode AND
                                so.VendorID=@VendorID";

                if (jobDate == null || "".Equals(jobDate))
                {
                    sqlStr += " AND soDtl.JobDate IS NULL;";
                }
                else
                {
                    sqlStr += " AND soDtl.JobDate = @JobDate;";
                }

                parmsList.Add(new SqlParameter("@TruckStatusID" + hidTruckStatusID.Value, hidTruckStatusID.Value));
            }
        }

        if (!"".Equals(sqlStr))
        {
            if (trackingManager.AddTracking(sqlStr, parmsList.ToArray()))
            {
                gvSendTruckList_SelectedIndexChanged(sender, e);
                dataBind();
                return;
            }
            else
            {
                Jscript.Alert(Resources.Messages.AddFailed, this.Page);
            }
        }
    }

    protected void btnAddSShipper_Click(object sender, EventArgs e)
    {
        if (lstShipper.SelectedValue != string.Empty)
        {
            for (int i = 0; i < lstShipper.Items.Count; i++)
            {
                bool issel = false;
                if (lstShipper.Items[i].Selected)
                {
                    for (int j = 0; j < lstSelShipper.Items.Count; j++)
                    {
                        if (lstShipper.Items[i].Value == lstSelShipper.Items[j].Value)
                        {
                            issel = true;
                            break;
                        }
                    }

                    if (!issel)
                    {
                        ListItem item = new ListItem();
                        item.Text = lstShipper.Items[i].Text;
                        item.Value = lstShipper.Items[i].Value;
                        lstSelShipper.Items.Add(item);
                    }
                }
            }
        }
        else
        {

        }

    }
    protected void btnDeleteSShipper_Click(object sender, EventArgs e)
    {
        if (lstSelShipper.Items.Count > 0)
        {
            ListItemCollection lstColl = new ListItemCollection();
            for (int i = 0; i < lstSelShipper.Items.Count; i++)
            {
                if (!lstSelShipper.Items[i].Selected)
                {
                    ListItem item = new ListItem(lstSelShipper.Items[i].Text, lstSelShipper.Items[i].Value);
                    lstColl.Add(item);
                }
            }
            if (lstColl != null && lstColl.Count > 0)
            {
                lstSelShipper.Items.Clear();
                for (int j = 0; j < lstColl.Count; j++)
                {
                    lstSelShipper.Items.Add(lstColl[j]);
                }
            }
            else
            {
                lstSelShipper.Items.Clear();
            }

        }
    }

}
